package com.ecp.commons.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class URLRedir extends HttpServlet {

	private static final long	serialVersionUID				= 1L;
	public static final String	PARAMETER_PREFIX_NAME			= "prefix";
	public static final String	PARAMETER_PREFIX_CONTEXTPATH	= "context";
	public static final String	PARAMETER_URL_NAME				= "url";

	public URLRedir() {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = request.getParameter(PARAMETER_URL_NAME);
		url.replace("&", "&amp");
		if (url == null || url.equals("")) {
			return;
		}
		String area = request.getParameter("Area");
		if (area != null && !area.trim().equals("")) {
			url = url + "&Area=" + area;
		}

		String prefix = request.getParameter(PARAMETER_PREFIX_NAME);
		if (prefix != null && prefix.equalsIgnoreCase(PARAMETER_PREFIX_CONTEXTPATH)) {
			url = request.getContextPath() + "/" + url;
		}

		@SuppressWarnings("unchecked")
		Map<String, Object> pMap = request.getParameterMap();

		try {
			Iterator<String> it = pMap.keySet().iterator();
			while (it.hasNext()) {
				String pName = (String) it.next();
				String pValue = request.getParameter(pName);
				if (pName != null && !pName.equals(PARAMETER_PREFIX_NAME) && !pName.equals(PARAMETER_URL_NAME)) {
					if (url.indexOf("?") < 0) {
						url += "?" + pName + "=" + pValue;
					} else {
						url += "&" + pName + "=" + pValue;
					}
				}
			}
		} catch (Exception e) {
		}

		response.sendRedirect(url);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
